import Vue from 'vue';
import Router from 'vue-router';
import HomePage from './views/HomePage.vue';
import UserManagement from './views/UserManagement.vue';
import ProductManagement from './views/ProductManagement.vue';
import OrderManagement from './views/OrderManagement.vue';
import LoginPage from './components/Login.vue'; // 确保路径正确

Vue.use(Router);

const routes = [
  { path: '/', component: LoginPage, name: 'Login' }, // 设置默认路由为登录页面
  { path: '/home', component: HomePage, name: 'Home' },
  { path: '/users', component: UserManagement, name: 'UserManagement' },
  { path: '/products', component: ProductManagement, name: 'ProductManagement' },
  { path: '/orders', component: OrderManagement, name: 'OrderManagement' },
];

const router = new Router({
  mode: 'history', // 使用 HTML5 History 模式，去掉 URL 中的哈希 (#)
  routes,
});

//添加路由守卫
router.beforeEach((to, from, next) => {
  const token = window.sessionStorage.getItem('token');

  // 如果要访问的路由是登录页面，不需要验证
  if (to.name === 'Login') {
    next();
  } else {
    // 需要验证的页面
    if (token) {
      next(); // 有 token，放行
    } else {
      next({ name: 'Login' }); // 没有 token，重定向到登录页面
    }
  }
});

// 修改 Router 实例的 push 方法
const originalPush = Router.prototype.push;
Router.prototype.push = function push(location, onResolve, onReject) {
  if (onResolve || onReject) {
    return originalPush.call(this, location, onResolve, onReject);
  }
  return originalPush.call(this, location).catch(err => err);
};

export default router;
